<template>
  <div class="config-panel">
    <el-card class="config-card">
      <template #header>
        <div class="card-header">
          <h3>⚙️ 配置面板</h3>
        </div>
      </template>

      <div class="config-content">
        <el-form :model="config" label-width="140px">
          <el-form-item label="分析数据文件:">
            <el-select
              v-model="selectedDataPath"
              placeholder="选择分析数据文件"
              style="width: 100%"
              @change="handleDataPathChange"
            >
              <el-option
                v-for="option in dataPathOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="自定义路径:">
            <el-input
              v-model="customPath"
              placeholder="输入自定义分析数据文件路径"
              @change="handleCustomPathChange"
            >
              <template #append>
                <el-button @click="loadCustomPath">加载</el-button>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="当前配置:">
            <el-descriptions :column="1" size="small">
              <el-descriptions-item label="数据路径">
                {{ config.analysisDataPath }}
              </el-descriptions-item>
              <el-descriptions-item label="当前加载">
                <el-tag :type="isLoading ? 'warning' : 'success'" size="small">
                  {{ isLoading ? '加载中...' : currentFilePath || '未加载' }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="缓存状态">
                {{ config.cacheEnabled ? '启用' : '禁用' }}
              </el-descriptions-item>
              <el-descriptions-item label="缓存时间">
                {{ config.cacheExpireTime }}分钟
              </el-descriptions-item>
              <el-descriptions-item label="运行模式">
                {{ config.mode }}
              </el-descriptions-item>
              <el-descriptions-item label="版本">
                {{ config.appVersion }}
              </el-descriptions-item>
            </el-descriptions>
          </el-form-item>

          <el-form-item label="缓存管理:">
            <div class="cache-management">
              <el-button size="small" @click="showCacheStats">
                📊 缓存统计
              </el-button>
              <el-button size="small" @click="clearAllCache">
                🗑️ 清除缓存
              </el-button>
              <el-button size="small" @click="preloadCommonData">
                🚀 预加载
              </el-button>
            </div>
          </el-form-item>
        </el-form>

        <div class="actions">
          <el-button type="primary" @click="reloadData">
            🔄 重新加载数据
          </el-button>
          <el-button @click="resetConfig">
            🔄 重置配置
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, type Ref } from 'vue';
import { ElMessage } from 'element-plus';
import { useAnalysisStore } from '../stores/analysis-store';
import { EnvironmentConfig } from '../utils/environment';
import { AnalysisDataService } from '../services/analysis-data';

// 使用全局状态管理
const { currentFilePath, isLoading } = useAnalysisStore();

// 响应式数据
const config: Ref<any> = ref({});
const selectedDataPath: Ref<string> = ref('');
const customPath: Ref<string> = ref('');
const analysisService = AnalysisDataService.getInstance();

// 数据路径选项
const dataPathOptions = [
  { label: '测试数据', value: '/analysis/test-analysis.json' },
  { label: 'PaasMainFront', value: '/analysis/gct-paas-analysis.json' },
  { label: 'PaasPackage', value: '/analysis/paas-package-analysis.json' },
  { label: 'PaasPackageProjects', value: '/analysis/projects-analysis.json' },
];

// 事件定义
const emit = defineEmits<{
  dataReloaded: []
}>();

/**
 * 处理数据路径变更
 */
const handleDataPathChange = async (path: string): Promise<void> => {
  try {
    await analysisService.loadAnalysisData(path);
    ElMessage.success(`已切换到: ${path}`);
    emit('dataReloaded');
  } catch (error) {
    ElMessage.error(`加载失败: ${error instanceof Error ? error.message : '未知错误'}`);
  }
};

/**
 * 处理自定义路径变更
 */
const handleCustomPathChange = (path: string): void => {
  customPath.value = path;
};

/**
 * 加载自定义路径
 */
const loadCustomPath = async (): Promise<void> => {
  if (!customPath.value.trim()) {
    ElMessage.warning('请输入自定义路径');
    return;
  }

  try {
    await analysisService.loadAnalysisData(customPath.value);
    ElMessage.success(`已加载自定义路径: ${customPath.value}`);
    selectedDataPath.value = customPath.value;
    emit('dataReloaded');
  } catch (error) {
    ElMessage.error(`加载失败: ${error instanceof Error ? error.message : '未知错误'}`);
  }
};

/**
 * 重新加载数据
 */
const reloadData = async (): Promise<void> => {
  try {
    const path = selectedDataPath.value || config.value.analysisDataPath;
    await analysisService.loadAnalysisData(path);
    ElMessage.success('数据重新加载成功');
    emit('dataReloaded');
  } catch (error) {
    ElMessage.error(`重新加载失败: ${error instanceof Error ? error.message : '未知错误'}`);
  }
};

/**
 * 重置配置
 */
const resetConfig = (): void => {
  config.value = EnvironmentConfig.getConfig();
  selectedDataPath.value = config.value.analysisDataPath;
  customPath.value = '';
  ElMessage.info('配置已重置');
};

/**
 * 显示缓存统计
 */
const showCacheStats = (): void => {
  const stats = analysisService.getCacheStats();
  ElMessage.info({
    message: `缓存统计 - 缓存数量: ${stats.cacheSize}, 正在加载: ${stats.activeLoading}`,
    duration: 3000,
  });

  console.group('📊 缓存统计信息');
  console.log('缓存数量:', stats.cacheSize);
  console.log('正在加载:', stats.activeLoading);
  console.log('缓存路径:', stats.cacheKeys);
  console.log('加载路径:', stats.loadingKeys);
  console.groupEnd();
};

/**
 * 清除所有缓存
 */
const clearAllCache = (): void => {
  analysisService.clearCache();
  ElMessage.success('已清除所有缓存');
};

/**
 * 预加载常用数据
 */
const preloadCommonData = async (): Promise<void> => {
  try {
    const paths = dataPathOptions.map(option => option.value);
    const result = await analysisService.preloadData(paths);

    ElMessage.success(`预加载完成 - 成功: ${result.success.length}, 失败: ${result.failed.length}`);

    if (result.failed.length > 0) {
      console.warn('预加载失败的文件:', result.failed);
    }
  } catch (error) {
    ElMessage.error('预加载失败');
    console.error('预加载错误:', error);
  }
};

/**
 * 初始化配置
 */
const initConfig = (): void => {
  config.value = EnvironmentConfig.getConfig();
  selectedDataPath.value = config.value.analysisDataPath;
};

// 组件挂载时初始化
onMounted(() => {
  initConfig();
});
</script>

<style scoped>
.config-panel {
  margin-bottom: 20px;
}

.config-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header h3 {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.config-content {
  padding: 10px 0;
}

.actions {
  margin-top: 20px;
  text-align: center;
}

.actions .el-button {
  margin: 0 8px;
}

.cache-management {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.cache-management .el-button {
  margin: 0;
}

:deep(.el-descriptions-item__label) {
  width: 80px;
  font-weight: 600;
}
</style>
